package com.rs.game.minigames.pest.impl;

import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import com.rs.cores.CoresManager;
import com.rs.game.RegionBuilder;
import com.rs.game.WorldTile;
import com.rs.game.npc.NPC;
import com.rs.game.npc.others.PestPortal;
import com.rs.game.player.Player;
import com.rs.utils.Utils;

	public class PestControl {

		private List<Player> team;
		
		private int[] boundChunks;

		private final Object lock = new Object();

		public static final WorldTile OUTSIDE_AREA = new WorldTile(2657, 2639, 0);

		public PestPortal[] portals = new PestPortal[4];

		private NPC knight;

		class PestGameTimer extends TimerTask {

			int minutes = 0;

			@Override
			public void run() {
				if (minutes == 20 || knight.isDead())
					endGame();
				minutes++;
			}
		}

		public PestControl(final List<Player> team) {// OMFG IMPORTANT COORDS <3
														// 2614, 2568
			this.team = team;
			CoresManager.slowExecutor.schedule(new TimerTask() {
				@Override
				public void run() {
					boundChunks = RegionBuilder.findEmptyChunkBound(8, 8);
					RegionBuilder.copyAllPlanesMap(328, 320, boundChunks[0], boundChunks[1], 8);
					CoresManager.slowExecutor.schedule(new TimerTask() {
						@Override
						public void run() {
							sendBeginningWave();
							for (Player player : team)
								player.setNextWorldTile(getWorldTile(35 - Utils.random(4), 54 - (Utils.random(3))));
						}
					}, 1200, TimeUnit.MILLISECONDS);
				}
			}, 1200, TimeUnit.MILLISECONDS);
		}

		private void sendBeginningWave() {
			knight = new PestPortal(3782, getWorldTile(32, 32));
			int portalIndex = 6142;
			for (int index = 0; index < portals.length; index++)
				portals[index] = new PestPortal(portalIndex++, getPortalWorldTiles()[index]);
		}

		public WorldTile[] getPortalWorldTiles() {
			return new WorldTile[] { getWorldTile(4, 31),// purple
					getWorldTile(56, 28),// blue
					getWorldTile(45, 10),// yellow
					getWorldTile(21, 9) };// light pink
		}

		public WorldTile getWorldTile(int mapX, int mapY) {
			return new WorldTile(boundChunks[0] * 8 + mapX, boundChunks[1] * 8 + mapY, 0);
		}

		public void endGame() {
			for (Player player : team) {
				synchronized (lock) {
					player.setNextWorldTile(OUTSIDE_AREA);
					player.reset();
					player.getControlerManager().forceStop();
				}
			}
			CoresManager.slowExecutor.schedule(new TimerTask() {
				@Override
				public void run() {
					RegionBuilder.destroyMap(boundChunks[0], boundChunks[1], 8, 8);
				}
			}, 1200, TimeUnit.MILLISECONDS);
			team.clear();
		}

		public List<Player> getPlayers() {
			return team;
		}

		public NPC getKnight() {
			return knight;
		}
	}